package basemod

import (
	"gitee.com/wint/tge/log"
)

type RecverRange struct {
	id1 	uint16
	id2 	uint16
	recver IRecver
}

// 网络协议数据分发模块
type NetDispatcherMod struct {
	BaseMod

	singles	map[uint16]IRecver	// 单个接收者
	recvers	[]*RecverRange		// 范围接收者
}

func (this *NetDispatcherMod) Init() {
	this.BaseMod.Init()
	this.SetImpl(this)

	this.singles = make(map[uint16]IRecver)
}

func (this *NetDispatcherMod) AddSingle(id uint16, r IRecver) {
	this.Lock()
	this.Unlock()

	if _, ok := this.singles[id]; ok {
		log.Print("NetDispatcherMod Error: register mult recver id", id)
	}
	this.singles[id] = r
}

func (this *NetDispatcherMod) AddRecver(id1 uint16, id2 uint16, r IRecver) {
	this.Lock()
	this.Unlock()

	for _, v := range this.recvers {
		if (id1 >= v.id1 && id1 < v.id2) || (id2 >= v.id1 && id2 < v.id2) {
			log.Print("NetDispatcherMod Error: register mult recver range", id1, id2, v.id1, v.id2)
		}
	}
	this.recvers = append(this.recvers, &RecverRange{id1, id2, r})
}

func (this *NetDispatcherMod) OnRecv(pack IMsgPack) {
	this.RLock()
	defer this.RUnlock()

	id := pack.GetMsg().GetProtoId()
	if r, ok := this.singles[id]; ok {
		r.OnRecv(pack)
		return
	}
	for _, v := range this.recvers {
		if v.id1 <= id && v.id2 > id {
			v.recver.OnRecv(pack)
			return
		}
	}
}

var NetDispatcher = &NetDispatcherMod{}